import { ElMessage } from 'element-plus'
import type { Directive } from 'vue'
import router from './router'
import { useMenuStore } from './stores/menu'
import { useTokenStore } from './stores/token'
import Logger from './util/log'
import { logoutResult } from './util/session'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'

NProgress.configure({
  easing: 'ease', // 动画方式
  showSpinner: false, // 是否显示加载ico
}) // NProgress Configuration

const whiteList = ['/login', '/register'] // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const tokenStore = useTokenStore()
  const menuStore = useMenuStore()
  // Logger.prettyInfo(
  //   'before each routes',
  //   to.path,
  //   menuStore.getMenuList().length,
  //   router.getRoutes(),
  // )
  // 判断是否有token
  if (tokenStore.getToken()) {
    if (to.path === '/login') {
      NProgress.done()
      next()
    } else {
      if (menuStore.getMenuList() && menuStore.getMenuList().length > 0) {
        // Logger.prettyInfo('menuStore.getMenuList()', menuStore.getMenuList())
        next()
      } else {
        try {
          // 动态添加路由
          await menuStore.refreshMenuList()
          next({ ...to, replace: true })
        } catch (error) {
          Logger.prettyError('permission error', error)
          ElMessage.error('权限获取失败: ' + error.response.data.msg)
          logoutResult()
          next(`/login?redirect=${to.path}`) // 将跳转的路由path作为参数，登录成功后跳转到该路由
        }
      }
    }
  } else {
    // 如果没有token，则判断是否在白名单中
    if (whiteList.indexOf(to.path) !== -1) {
      // 如果在白名单中，则直接进入
      next()
    } else {
      // 如果不在白名单中，则重定向到登录页
      Logger.warn('登陆失效，跳转到登录页......')
      next(`/login?redirect=${to.path}`) // 将跳转的路由path作为参数，登录成功后跳转到该路由
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export const opPermission: Directive = {
  mounted(el, binding) {
    const { value } = binding
    const menuStore = useMenuStore()
    const permissions = menuStore.getAuthList()
    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value
      const hasPermission = permissions.some((role) => {
        return permissionRoles.includes(role)
      })
      if (!hasPermission) {
        el.style.display = 'none'
      }
    } else {
      throw new Error(`need roles! Like v-permission="['admin','editor']"`)
    }
  },
}
